package com.excesys.exsecs.scada.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.excesys.exsecs.common.core.util.R;
import com.excesys.exsecs.scada.entity.ScadaSystemBind;
import com.excesys.exsecs.scada.mapper.ScadaSystemBindMapper;
import com.excesys.exsecs.scada.service.ScadaSystemBindService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 系统参数与组态绑定
 *
 * @author tzh
 * @date 2024-12-09 10:43:01
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/scadaSystemBind" )
@Tag(description = "scadaSystemBind" , name = "系统参数管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ScadaSystemBindController {

	private final ScadaSystemBindService systemBindService;
	private final ScadaSystemBindMapper bindMapper;

	@Operation(summary = "新增绑定" , description = "新增绑定" )
	@PostMapping("/bind")
	public R bind(@RequestBody ScadaSystemBind systemBind){
		//清除旧数据
		bindMapper.delete(Wrappers.<ScadaSystemBind>lambdaQuery()
				.eq(ScadaSystemBind::getScadaId,systemBind.getScadaId()));
		//新增
		List<ScadaSystemBind> bindList = new ArrayList<>();
		if(ObjectUtil.isNotNull(systemBind.getScadaId()) && ObjectUtil.isNotNull(systemBind.getUnitNos()) && systemBind.getUnitNos().size()>0){
			systemBind.getUnitNos().forEach(item->{
				ScadaSystemBind ssb = new ScadaSystemBind();
				ssb.setScadaId(systemBind.getScadaId());
				ssb.setUnitNo(item);
				bindList.add(ssb);
			});
		}
		return R.ok(systemBindService.saveBatch(bindList),"新增系统参数与组态绑定");
	}

	/**
	 * 根据组态id查询已经绑定的设备
	 */
	@Operation(summary = "回显" , description = "回显" )
	@GetMapping("/getUnitNos")
	public R getUnitNos(Long scadaId){
		List<ScadaSystemBind> bindList = bindMapper.selectList(Wrappers.<ScadaSystemBind>lambdaQuery().eq(ScadaSystemBind::getScadaId, scadaId));
		if(ObjectUtil.isNotNull(bindList) && bindList.size()>0){
			List<String> collect = bindList.stream().map(ScadaSystemBind::getUnitNo).collect(Collectors.toList());
			return R.ok(collect,"成功");
		}
		return R.ok(null,"没有绑定");
	}



}
